// pages/roomPattern/editRoom.js
var util = require('../../utils/util.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: '', // 登录用户信息
    id: '', // 房源编号
    configList: [], // 房间配置
    configId: [], // 已选配置
    imgs: [], // 房间图片
    configHidden: true, // 房间配置框状态
    videoUrl: '', // 视频URL
    videoId: 0, // 视频编号
    room_code: '', // 房间号
    room_floor: '', // 所在楼层
    total_floor: '', // 公寓总楼层
    build_area: '', // 面积
    month_earnest: '', // 定金
    month_rent: '', // 租金
    month_depost: '', // 押金
    network_cost: '', // 网费
    manage_cost: '', // 管理费
    custom_name: '', // 其他费用名称
    custom_cost: '', // 其他费用金额
    rent_day: '', // 收租日
    watermeter_no: '', // 水表号
    ele_no: '', // 电表号
    room_remark: '', // 描述
    service_surplus: '', // 服务余额
    ossFile: [], // 被移除的OSS图片or视频
    disabledBtn: false, // 提交按钮状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var id = options.id; // 房源编号
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        var data = res.data;
        that.setData({
          userInfo: data,
          id: id
        });
        wx.showLoading({
          title: '加载中···'
        })
        that.getRoomInfo();
        wx.hideLoading();
      },
      fail: function () {
        wx.redirectTo({
          url: '/pages/index/index',
        })
      }
    });
  },

  /**
   * 获取房间信息
   */
  getRoomInfo: function () {
    var that = this;
    var data = that.data;

    var id = data.id; // 房源编号
    var userInfo = data.userInfo; // 登录人信息
    var uid = userInfo.user_id; // 登录人ID
    var source = userInfo.source; // 登录人房东ID
    var user_type_id = userInfo.user_type_id; // 账号类型
    util.getReq('/app/home/roomInfoInterface', {
      'user_type_id': user_type_id,
      'room.room_id': id
    }, function (data) {
      if (data.code == 0) {
        var params = data.params;
        var configList = params.configList; // 初始配置信息
        var configDtails = params.configDtails; //房间配置信息
        var imgs = params.imgs; //房间图片集合
        var rooms = params.rooms;
        // 筛选已配置的设施
        var newConfigList = [];
        for (var i = 0; i < configList.length; i++) {
          var checked = false;
          for (var k = 0; k < configDtails.length; k++) {
            if (configList[i].config_id == configDtails[k].config_id) {
              checked = true;
              break;
            }
          }
          var s = {
            'key': configList[i].config_name,
            'val': configList[i].config_id,
            'checked': checked
          };
          newConfigList.push(s);
        }

        //重构已配置设施数据结构
        var configId = [];
        for (var i = 0; i < configDtails.length; i++) {
          configId.push(configDtails[i].config_id);
        }
        that.setData({
          room_show: rooms.room_show, // 出租状态
          room_code: rooms.room_code, // 房间号
          room_floor: rooms.room_floor, // 所在楼层
          total_floor: rooms.total_floor, // 公寓总楼层
          build_area: rooms.build_area, // 面积
          month_earnest: rooms.month_earnest, // 定金
          deposit_num: rooms.deposit_num, //押金月数
          rent_num: rooms.rent_num, //租金月数
          month_rent: rooms.month_rent, // 租金
          month_depost: rooms.month_depost, // 押金
          network_cost: rooms.network_cost, // 网费
          manage_cost: rooms.manage_cost, // 管理费
          custom_name: rooms.custom_name, // 其他费用名称
          custom_cost: rooms.custom_cost, // 其他费用金额
          rent_day: rooms.rent_day, // 收租日
          watermeter_no: rooms.watermeter_no, // 水表号
          ele_no: rooms.ele_no, // 电表号
          room_remark: rooms.room_remark, // 描述
          service_surplus: params.service_surplus, // 服务余额
          videoUrl: rooms.video_url, // 房间视频
          videoId: rooms.video_id, // 视频编号
          configList: newConfigList, // 房间配置
          configId: configId, // 已选配置
          imgs: imgs, // 房间图片
        });
      } else {
        util.isError(data.desc);
      }
    });
  },

  /**
   * 提交
   */
  submit: function () {
    var that = this;
    var d = that.data;
    if (d.videoUrl != 'null' && d.videoId == 0) {
      that.setData({
        disabledBtn: true
      });
      const uploadTask = wx.uploadFile({
        url: 'https://landlord.kuailezufang.com/app/home/upload',
        filePath: d.videoUrl,
        method: 'post',
        name: 'file',
        formData: {
          "params": "room",
        },
        success: function (res) {
          let data = JSON.parse(res.data);
          if (data.code == 0) {
            that.setData({
              videoUrl: data.data
            });
            that.saveInfo();
          }
        }
      });
      uploadTask.onProgressUpdate((res) => {
        if (res.progress < 100) {
          wx.showLoading({
            title: '视频上传' + res.progress + '%',
          });
        } else {
          wx.showLoading({
            title: '提交中···',
          });
        }
      });
    } else {
      that.saveInfo();
    }
  },

  /**
   * 最终保存
   */
  saveInfo: function () {
    var that = this;
    var d = that.data;
    that.setData({
      disabledBtn: true
    });
    wx.showLoading({
      title: '提交中···',
    });
    util.getReq('/app/home/updateRoomInfo', {
      'room.room_id': d.id,
      'room.room_code': d.room_code,
      'room.room_floor': d.room_floor,
      'room.total_floor': d.total_floor,
      'room.month_earnest': d.month_earnest,
      'room.build_area': d.build_area,
      'room.watermeter_no': d.watermeter_no,
      'room.ele_no': d.ele_no,
      'room.month_rent': d.month_rent,
      'room.month_depost': d.month_depost,
      'room.rent_day': d.rent_day,
      'room.network_cost': d.network_cost,
      'room.manage_cost': d.manage_cost,
      'room.custom_name': d.custom_name,
      'room.custom_cost': d.custom_cost,
      'room.room_remark': d.room_remark,
      'configInfo': JSON.stringify(d.configId), //配置信息
      'imgUrlJson': JSON.stringify(d.imgs), //图片url
      'video.video_url': d.videoUrl, //视频url
      'video.video_id': d.videoId, //视频id
      'ossFile': JSON.stringify(d.ossFile),
    }, function (data) {
      if (data.code == 0) {
        wx.showToast({
          title: '修改成功',
        });
        setTimeout(function () {
          that.getRoomInfo()
        }, 1000);
      } else {
        util.isError(data.desc);
      }
      that.setData({
        disabledBtn: false
      });
    });
    wx.hideLoading();
  },

  /**
   * 展示配置项
   */
  onConfig: function () {
    var that = this;
    that.setData({
      configHidden: false
    });
  },

  /**
   * 勾选配置项事件
   */
  checkboxChange: function (e) {
    var value = e.detail.value;
    var id = [];
    for (var i = 0; i < value.length; i++) {
      id.push(value[i]);
    }
    this.setData({
      configId: id
    });
  },

  /**
   * 确定
   */
  onConfirm: function () {
    var that = this;
    that.setData({
      configHidden: true
    });
  },

  /**
   * 取消
   */
  onCancel: function () {
    var that = this;
    that.setData({
      configHidden: true
    });
  },

  /**
   * 选择图片
   */
  chooseImage: function () {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: function (res) {
        wx.showLoading({
          title: '上传中···',
        });
        var tempFiles = res.tempFiles;
        console.log(tempFiles);
        var isSize = false; // 是否有图片大于2M
        for (var i = 0; i < tempFiles.length; i++) {
          if (tempFiles[i].size / 1024 / 1024 <= 2) {
            wx.uploadFile({
              url: 'https://landlord.kuailezufang.com/app/home/upload',
              filePath: tempFiles[i].path,
              method: 'post',
              name: 'file',
              formData: {
                'params': 'roomImg'
              },
              success: function (res) {
                let data = JSON.parse(res.data);
                console.log(data);
                if (data.code == 0) {
                  that.data.imgs.push({
                    'img_url': data.data,
                    'img_id': 0
                  });
                  that.$imgs();
                } else {
                  util.isError(data.desc);
                }
              }
            });
          } else {
            isSize = true;
          }
        }
        wx.hideLoading();
        if (isSize) {
          util.isError('图片大小不能大于2M');
        }
      }
    });
  },

  /**
   * 移除图片
   */
  removeImage(e) {
    var dataset = e.target.dataset;
    var idx = dataset.idx;
    var src = dataset.src;
    if (src.indexOf('klzf.oss-cn-shenzhen.aliyuncs.com') != -1) {
      this.data.ossFile.push(src.substring(41, src.length));
    }
    this.data.imgs.splice(idx, 1);
    this.$imgs();
  },

  /**
   * 选择或拍摄视频
   */
  chooseVideo: function () {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 15,
      camera: ['front', 'back'],
      success: function (res) {
        that.setData({
          videoUrl: res.tempFilePath,
          videoId: 0
        })
      }
    });
  },

  /**
   * 移除视频
   */
  removeVideo: function () {
    var videoUrl = this.data.videoUrl;
    if (videoUrl.indexOf('klzf.oss-cn-shenzhen.aliyuncs.com') != -1) {
      this.data.ossFile.push(videoUrl.substring(41, videoUrl.length));
    }
    this.setData({
      videoUrl: 'null',
      videoId: 0
    });
  },

  /**
   * 图片预览
   */
  handleImagePreview(e) {
    var idx = e.target.dataset.idx;
    var imgs = this.data.imgs;
    var newimgs = [];
    for (var i = 0; i < imgs.length; i++) {
      newimgs.push(imgs[i].img_url);
    }
    wx.previewImage({
      current: newimgs[idx], //当前预览的图片
      urls: newimgs, //所有要预览的图片
    })
  },

  $imgs: function () {
    this.setData({
      imgs: this.data.imgs
    });
  },

  room_code: function (e) {
    this.setData({
      room_code: e.detail.value
    })
  },

  room_floor: function (e) {
    this.setData({
      room_floor: e.detail.value
    })
  },

  build_area: function (e) {
    this.setData({
      build_area: e.detail.value
    })
  },

  month_earnest: function (e) {
    this.setData({
      month_earnest: e.detail.value
    })
  },

  month_rent: function (e) {
    var value = e.detail.value;
    var deposit_num = this.data.deposit_num;
    this.setData({
      month_rent: value
    })
    if (deposit_num != -1) {
      this.setData({
        month_depost: value * deposit_num
      })
    }
  },

  month_depost: function (e) {
    this.setData({
      month_depost: e.detail.value
    })
  },

  network_cost: function (e) {
    this.setData({
      network_cost: e.detail.value
    })
  },

  manage_cost: function (e) {
    this.setData({
      manage_cost: e.detail.value
    })
  },

  custom_name: function (e) {
    this.setData({
      custom_name: e.detail.value
    })
  },

  custom_cost: function (e) {
    this.setData({
      custom_cost: e.detail.value
    })
  },

  rent_day: function (e) {
    this.setData({
      rent_day: e.detail.value
    })
  },

  watermeter_no: function (e) {
    this.setData({
      watermeter_no: e.detail.value
    })
  },

  ele_no: function (e) {
    this.setData({
      ele_no: e.detail.value
    })
  },

  room_remark: function (e) {
    this.setData({
      room_remark: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
  
})